
// cookie 操作
const cookie = {
  set: function (name, val, day = 30) {
    let expireDate = new Date();
    expireDate.setDate(expireDate.getDate() + day);
    document.cookie = `${name}=${val};path="/";expires=${expireDate.toGMTString()}`;
  },
  get: function (name) {
    var cookieStr = document.cookie.replace(/\s+/g, "");  //清楚空格
    var str = cookieStr.split(";");        //将cookie分割成数组
    for (var i = 0; i < str.length; i++) {
      var newStr = str[i].split("=");
      if (newStr[0] == name) {
        return newStr[1];
      }
    }
  },
  delete: function (name) {
    let cookies = this.get();
    if (cookies) {
      for (let cookie of cookies) {
        if (cookie.name === name) {
          this.set(name, null, -99);
          break;
        }
      }
    } else {
      return false;
    }
  }
}


// 获取地址栏参数
function getUrlQuery(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  var result = window.location.search.substr(1).match(reg);
  if (result != null) {
    return unescape(result[2]);
  }
  return null;
}


function toDate(number) {
  var n = number * 1000;
  var date = number ? new Date(n) : new Date();
  var Y = date.getFullYear();
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
  var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  return (Y + '-' + M + '-' + D)
}
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
function toDate2(number) {
  var dateTime = new Date(parseInt(number) * 1000)
  var year = dateTime.getFullYear();
  var month = dateTime.getMonth() + 1;
  var day = dateTime.getDate();
  var hour = dateTime.getHours() < 10 ? "0" + dateTime.getHours() : dateTime.getHours();
  var minute = dateTime.getMinutes() < 10 ? "0" + dateTime.getMinutes() : dateTime.getMinutes();
  var second = dateTime.getSeconds();
  var now = new Date();
  var now_new = Date.parse(now.toDateString());  //typescript转换写法
  var milliseconds = now_new - dateTime;
  var timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
  return timeSpanStr;
}



export default {
  cookie,
  getUrlQuery,
  toDate,
  formatTime,
  toDate2
}

export {
  cookie,
  getUrlQuery,
  toDate,
  formatTime,
  toDate2
}